<template>
  <div class="timer-container">
    <!-- <span>订单结束还有:</span> -->
    <div class="timer-container-box" v-if="remainingTime">
      <span style="color: #b52421">{{ remainingTime }}</span>
    </div>
  </div>
</template>
<script>
export default {
  inheritAttrs: false, // 在组件选项中设置 inheritAttrs
};
</script>
<script setup>
import {
  onMounted,
  onUnmounted,
  ref,
  reactive,
  onBeforeUnmount,
  toRefs,
} from "vue";

const props = defineProps({
  orderCreatedTime: String,
  duration: Number,
});
const Flag = ref(false);
const emit = defineEmits(["timechange"]);

const { orderCreatedTime, duration } = toRefs(props);
console.log(orderCreatedTime.value, duration.value, "======================");
const remainingTime = ref(null);
const countdownInterval = ref(null);
onMounted(() => {
  startCountdown();
});
onBeforeUnmount(() => {
  stopCountdown();
});
const startCountdown = () => {
  Flag.value = true;
  const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（以秒为单位）
  const endTime =
    new Date(orderCreatedTime.value).getTime() / 1000 + duration.value; // 结束时间戳（以秒为单位）
  var remainingSeconds = endTime - currentTime;
  remainingTime.value = formatTime(remainingSeconds);
  countdownInterval.value = setInterval(() => {
    if (remainingSeconds > 0) {
      remainingSeconds--;
      remainingTime.value = formatTime(remainingSeconds);
      emit("timechange", {
        remainingTime: remainingTime.value,
        djs: true,
      });
    } else {
      remainingTime.value = 0;
      Flag.value = false;

      emit("timechange", { remainingTime: remainingTime.value, djs: false });
      stopCountdown();
    }
  }, 1000);
};
const stopCountdown = () => {
  clearInterval(countdownInterval.value);
  countdownInterval.value = null;
};
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${padZero(minutes)}:${padZero(secs)}`;
};
const padZero = (num) => {
  return String(num).padStart(2, "0");
};
</script>

<style lang="scss">
.timer-container {
  .timer-container-box {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
/* 样式可以根据需要自定义 */
</style>
